package org.example.leetcode;

/**
 * @version 1.0.0
 * @author: lynn
 * @description: 删除链表中的倒数第n个节点
 * @date: 2021/7/26 19:38
 */
public class LC19 {
    public static void main(String[] args) {

    }

    //fixme 最好要画执行过程
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fastNode=head;
        ListNode slowNode=head;
        while (n>0){
            fastNode=fastNode.next;
            n--;
        }
        if (fastNode==null)
            return head.next;
        //fixme 前面做了判空
        while (fastNode.next!=null){
            slowNode=slowNode.next;
            fastNode=fastNode.next;
        }
        //此时要删除的就是slow的下一个节点
        slowNode.next=slowNode.next.next;
        return head;
    }


    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
